package com.deyou.activity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.deyou.Constants;
import com.deyou.PayResult;
import com.deyou.R;
import com.deyou.base.BaseActivity;
import com.deyou.callback.ServerApi;
import com.deyou.model.HouseResourceDetailBean;
import com.deyou.model.LzyResponse;
import com.deyou.model.OrderBean;
import com.deyou.model.PayInfoBean;
import com.deyou.util.AESUtil;
import com.deyou.util.AndroidUtils;
import com.deyou.util.DateUtil;
import com.deyou.util.GlideImageLoader;
import com.deyou.util.SPUtils;
import com.deyou.util.Urls;
import com.google.gson.jpush.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class PayOrderActivity extends BaseActivity {

    @BindView(R.id.tv_mid_title)
    TextView tvMidTitle;
    @BindView(R.id.alipay_layout)
    RelativeLayout alipayLayout;
    @BindView(R.id.wechat_layout)
    RelativeLayout wechatLayout;
    @BindView(R.id.bank_card_layout)
    RelativeLayout bankCardLayout;
    @BindView(R.id.paypal_layout)
    RelativeLayout paypalLayout;
    @BindView(R.id.btn_pay)
    TextView btnPay;
    @BindView(R.id.iv_choosed_alipay)
    ImageView ivChoosedAlipay;
    @BindView(R.id.iv_choosed_wechat)
    ImageView ivChoosedWechat;
    @BindView(R.id.iv_choosed_bankcard)
    ImageView ivChoosedBankcard;
    @BindView(R.id.iv_choosed_paypal)
    ImageView ivChoosedPaypal;
    @BindView(R.id.iv_left_back)
    ImageView ivLeftBack;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.iv_right)
    ImageView ivRight;
    @BindView(R.id.title_view)
    RelativeLayout titleView;
    @BindView(R.id.iv_house)
    ImageView ivHouse;
    @BindView(R.id.tv_house_attr)
    TextView tvHouseAttr;
    @BindView(R.id.tv_house_price)
    TextView tvHousePrice;
    @BindView(R.id.tv_checkin_date)
    TextView tvCheckinDate;
    @BindView(R.id.tv_checkout_date)
    TextView tvCheckoutDate;
    @BindView(R.id.tv_total_days)
    TextView tvTotalDays;
    @BindView(R.id.btn_show_more_detail)
    TextView btnShowMoreDetail;
    @BindView(R.id.house_info_layout)
    RelativeLayout houseInfoLayout;
    @BindView(R.id.tv_total_money_title)
    TextView tvTotalMoneyTitle;
    @BindView(R.id.tv_total_money)
    TextView tvTotalMoney;
    @BindView(R.id.tv_house_fee_titel)
    TextView tvHouseFeeTitel;
    @BindView(R.id.tv_total_house_fee)
    TextView tvTotalHouseFee;
    @BindView(R.id.tv_clean_fee_titel)
    TextView tvCleanFeeTitel;
    @BindView(R.id.tv_clean_fee)
    TextView tvCleanFee;
    @BindView(R.id.tv_paytype_title)
    TextView tvPaytypeTitle;
    private int payType = 1;

    private static final int SDK_PAY_FLAG = 1;
    private String payInfo = "";

    private String orderId;
//    private HouseResourceDetailBean detailBean;
    private OrderBean.OrderDetail orderDetail;
    private long days;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    Bundle bundle = new Bundle();
//                    bundle.putString("payMoney", orderDetail.payAmount);
//                    bundle.putString("productId", orderDetail.productId);
//                    bundle.putString("productName", orderDetail.productTitle);
//                    bundle.putString("orderId", orderDetail.orderId);
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        bundle.putInt("payStatus", 1);
                    } else {
                        bundle.putInt("payStatus", 2);
//                        AndroidUtils.startNextActivity(PayModeActivity.this, PayErrorActivity.class, bundle, false);
                    }
                    AndroidUtils.startNextActivity(PayOrderActivity.this, PayResultActivity.class, bundle, false);
                    break;
                }
                default:
                    break;
            }
        }
    };

    private int orderType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay_order);
        ButterKnife.bind(this);
        tvMidTitle.setText("支付");
        initData();
        getOrderDetail();
    }

    private void initData() {
        orderId = getIntent().getExtras().getString("orderId");
    }

    private void initView() {
        if (null != orderDetail) {
            if (!TextUtils.isEmpty(orderDetail.resourcePic)) {
                new GlideImageLoader().displayImage(this, Urls.HouseResourceImageBaseUrl + orderDetail.resourcePic, ivHouse);
            } else {
                new GlideImageLoader().displayImage(this, R.drawable.img_default, ivHouse);
            }
            tvHouseAttr.setText(orderDetail.resourceType + "-" + orderDetail.regionName);
            tvHousePrice.setText(Constants.RMB_UNIT + orderDetail.resourcePrice);


            tvCheckinDate.setText("入住时间：" + orderDetail.checkindate);
            tvCheckoutDate.setText("退房时间：" + orderDetail.checkoutdate);

            days = (DateUtil.string2Date10(orderDetail.checkoutdate).getTime() - DateUtil.string2Date10(orderDetail.checkindate).getTime()) / (1000 * 60 * 60 * 24);
            tvTotalDays.setText("共：" + days + "晚");

            tvHouseFeeTitel.setText(Constants.RMB_UNIT + orderDetail.resourcePrice + "*" + days + "晚");
            tvTotalHouseFee.setText(Constants.RMB_UNIT + " " + (orderDetail.resourcePrice * days));
            tvCleanFee.setText(Constants.RMB_UNIT + " 0");
            tvTotalMoney.setText(Constants.RMB_UNIT + " " + orderDetail.orderAmount);
        }
    }

    @OnClick({R.id.iv_left_back, R.id.alipay_layout, R.id.wechat_layout, R.id.bank_card_layout, R.id.paypal_layout, R.id.btn_pay})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_left_back:
                finish();
                break;
            case R.id.alipay_layout:
                ivChoosedWechat.setVisibility(View.GONE);
                ivChoosedBankcard.setVisibility(View.GONE);
                ivChoosedPaypal.setVisibility(View.GONE);
                ivChoosedAlipay.setVisibility(View.VISIBLE);
                payType = 1;

                break;
            case R.id.wechat_layout:
                ivChoosedAlipay.setVisibility(View.GONE);
                ivChoosedBankcard.setVisibility(View.GONE);
                ivChoosedPaypal.setVisibility(View.GONE);
                ivChoosedWechat.setVisibility(View.VISIBLE);
                payType = 5;
                break;
            case R.id.bank_card_layout:
                ivChoosedAlipay.setVisibility(View.GONE);
                ivChoosedWechat.setVisibility(View.GONE);
                ivChoosedPaypal.setVisibility(View.GONE);
                ivChoosedBankcard.setVisibility(View.VISIBLE);
                payType = 3;
                break;
            case R.id.paypal_layout:
                ivChoosedAlipay.setVisibility(View.GONE);
                ivChoosedWechat.setVisibility(View.GONE);
                ivChoosedBankcard.setVisibility(View.GONE);
                ivChoosedPaypal.setVisibility(View.VISIBLE);
                payType = 4;
                break;
            case R.id.btn_pay:
                creatPayment();
                break;
        }
    }

    private void getOrderDetail() {
        JSONObject object = new JSONObject();
        try {
            object.put("orderId", orderId);
            String paramJson = object.toString();

            Type type = new TypeToken<LzyResponse<OrderBean.OrderDetail>>() {}.getType();
            ServerApi.<LzyResponse<OrderBean.OrderDetail>>getData(type, Urls.getOrderDetail, "", AESUtil.encrypt(paramJson))//
                    .subscribeOn(Schedulers.io())//
                    .doOnSubscribe(new Consumer<Disposable>() {
                        @Override
                        public void accept(@NonNull Disposable disposable) throws Exception {
                            showLoading();
                        }
                    })//
                    .map(new Function<LzyResponse<OrderBean.OrderDetail>, OrderBean.OrderDetail>() {
                        @Override
                        public OrderBean.OrderDetail apply(@NonNull LzyResponse<OrderBean.OrderDetail> response) throws Exception {
                            return response.data;
                        }
                    })//
                    .observeOn(AndroidSchedulers.mainThread())  //
                    .subscribe(new Observer<OrderBean.OrderDetail>() {
                        @Override
                        public void onSubscribe(@NonNull Disposable d) {
                            addDisposable(d);
                        }

                        @Override
                        public void onNext(@NonNull OrderBean.OrderDetail orderInfo) {
                            if (null != orderInfo) {
                                orderDetail = orderInfo;
                                initView();
                            } else {
                            }
                        }

                        @Override
                        public void onError(@NonNull Throwable e) {
                            e.printStackTrace();            //请求失败
                            dismissLoading();
                        }

                        @Override
                        public void onComplete() {
                            dismissLoading();
                        }
                    });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void creatPayment() {
        JSONObject object = new JSONObject();
        try {
            object.put("payNo", orderId);
            object.put("productName", orderDetail.resourceName);
            object.put("money", orderDetail.orderAmount);
            object.put("money", "0.01");
            object.put("payType", payType);
            object.put("orderType", orderType);
            object.put("bankId", "ICBC");
            object.put("minute", "30");
            String paramJson = object.toString();

            Type type = new TypeToken<LzyResponse<PayInfoBean>>() {
            }.getType();
            ServerApi.<LzyResponse<PayInfoBean>>getData(type, Urls.createPayment, "", AESUtil.encrypt(paramJson))//
                    .subscribeOn(Schedulers.io())//
                    .doOnSubscribe(new Consumer<Disposable>() {
                        @Override
                        public void accept(@NonNull Disposable disposable) throws Exception {
                            showLoading();
                        }
                    })//
                    .map(new Function<LzyResponse<PayInfoBean>, PayInfoBean>() {
                        @Override
                        public PayInfoBean apply(@NonNull LzyResponse<PayInfoBean> response) throws Exception {
                            return response.data;
                        }
                    })//
                    .observeOn(AndroidSchedulers.mainThread())  //
                    .subscribe(new Observer<PayInfoBean>() {
                        @Override
                        public void onSubscribe(@NonNull Disposable d) {
                            addDisposable(d);
                        }

                        @Override
                        public void onNext(@NonNull PayInfoBean mPayInfo) {
                            if (null != payInfo) {
                                payInfo = mPayInfo.orderinfo;
                                if (payType == 1)
                                    alipay();
                            } else {
                            }
                        }

                        @Override
                        public void onError(@NonNull Throwable e) {
                            e.printStackTrace();            //请求失败
                            dismissLoading();
                        }

                        @Override
                        public void onComplete() {
                            dismissLoading();
                        }
                    });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /*
    * 支付宝支付
    */
    private void alipay() {
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(PayOrderActivity.this);
                Map<String, String> result = alipay.payV2(payInfo, true);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }
}
